package com.bjpowernode.web.config;

import com.bjpowernode.enums.Code;
import com.bjpowernode.web.views.ResultView;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.time.DateTimeException;

/**
 * @description:
 * @author: panDeng_Zhu
 * @time: 2022/11/27 20:13
 */

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 定义多个方法，处理不同异常
     *
     * @ExceptionHandler : 表示当前方法 处理异常
     * value ：是一个数组，异常的类型
     * 表示当发生和value匹配的异常，执行当前方法
     * 方法的参数：Exception e 是程序中抛出的异常对象
     */
    @ExceptionHandler({ArithmeticException.class, NullPointerException.class})
    public ResultView doArithmeticException(Exception e) {
        System.out.println("程序中抛出异常：" + e);

        ResultView<String> resultView = ResultView.FAIL();
        resultView.setEnumCode(Code.THROW_EXCEPTION);
        return resultView;
    }

    @ExceptionHandler({NumberFormatException.class})
    public ResultView doNumberFormatException(Exception e) {
        System.out.println(" NumberFormatException 程序中抛出异常：" + e);
        ResultView<String> resultView = ResultView.FAIL();
        resultView.setEnumCode(Code.THROW_EXCEPTION);
        return resultView;
    }

    //处理其他异常
    @ExceptionHandler
    public ResultView doOtherException(Exception e) {
        ResultView<String> resultView = ResultView.FAIL();
        if (e instanceof ArrayIndexOutOfBoundsException) {
            resultView.setEnumCode(Code.NUMBERFORMAT_EXCEPTION);
        } else if (e instanceof DateTimeException) {
            resultView.setEnumCode(Code.NULLPOINTER_EXCEPTION);
        } else {
            resultView.setEnumCode(Code.THROW_EXCEPTION);
        }
        return resultView;
    }
}
